package com.cmeduSystem.common.flow.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.cmeduSystem.common.core.annotation.MyRequestBody;
import com.cmeduSystem.common.core.constant.ErrorCodeEnum;
import com.cmeduSystem.common.core.object.*;
import com.cmeduSystem.common.core.util.MyCommonUtil;
import com.cmeduSystem.common.core.util.MyModelUtil;
import com.cmeduSystem.common.core.util.MyPageUtil;
import com.cmeduSystem.common.flow.dto.FlowDelegateUserDto;
import com.cmeduSystem.common.flow.model.FlowDelegateUser;
import com.cmeduSystem.common.flow.model.constant.FlowDelegatedUserConfirmStatus;
import com.cmeduSystem.common.flow.service.FlowDelegateUserService;
import com.cmeduSystem.common.flow.vo.FlowDelegateUserVo;
import com.cmeduSystem.common.log.annotation.OperationLog;
import com.cmeduSystem.common.log.model.constant.SysOperationLogType;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 流程委托用户接口。
 *
 * @author xulei
 * @date 2025-09-04
 */
@Tag(name = "流程委托用户接口")
@Slf4j
@RestController
@RequestMapping("${common-flow.urlPrefix}/flowDelegateUser")
@ConditionalOnProperty(name = "common-flow.operationEnabled", havingValue = "true")
public class FlowDelegateUserController {

    @Autowired
    private FlowDelegateUserService flowDelegateUserService;

    /**
     * 新增流程委托用户数据。
     *
     * @param flowDelegateUserDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody FlowDelegateUserDto flowDelegateUserDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(flowDelegateUserDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        FlowDelegateUser flowDelegateUser = MyModelUtil.copyTo(flowDelegateUserDto, FlowDelegateUser.class);
        flowDelegateUser = flowDelegateUserService.saveNew(flowDelegateUser);
        return ResponseResult.success(flowDelegateUser.getId());
    }

    /**
     * 更新流程委托用户数据。
     *
     * @param flowDelegateUserDto 更新对象。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody FlowDelegateUserDto flowDelegateUserDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(flowDelegateUserDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        FlowDelegateUser flowDelegateUser = MyModelUtil.copyTo(flowDelegateUserDto, FlowDelegateUser.class);
        FlowDelegateUser originalFlowDelegateUser = flowDelegateUserService.getById(flowDelegateUserDto.getId());
        if (originalFlowDelegateUser == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (!flowDelegateUserService.update(flowDelegateUser, originalFlowDelegateUser)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除流程委托用户数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody(required = true) Long id) {
        if (!flowDelegateUserService.remove(id)) {
            String errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }

    /**
     * 列出我的委托列表。
     *
     * @param orderParam 排序参数。
     * @param pageParam  分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/listMyDelegate")
    public ResponseResult<MyPageData<FlowDelegateUserVo>> listMyDelegate(
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        try (Page<FlowDelegateUser> page = PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize())) {
            String orderBy = MyOrderParam.buildOrderBy(orderParam, FlowDelegateUser.class);
            List<FlowDelegateUser> flowDelegateUserList = flowDelegateUserService.getFlowDelegateUserList(orderBy);
            return ResponseResult.success(MyPageUtil.makeResponseData(flowDelegateUserList, FlowDelegateUserVo.class));
        }
    }

    /**
     * 更新被委托确认状态。
     *
     * @param delegateId    委托Id。
     * @param confirmStatus 确认状态，1: 接受，2: 拒绝。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/updateDelegatedUserConfirm")
    public ResponseResult<Void> updateDelegatedUserConfirm(
            @MyRequestBody(required = true) Long delegateId,
            @MyRequestBody(required = true) Integer confirmStatus) {
        if (!MyCommonUtil.equalsAny(confirmStatus,
                FlowDelegatedUserConfirmStatus.ACCEPTED, FlowDelegatedUserConfirmStatus.REJECTED)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "数据验证失败，无效的确认状态参数值！");
        }
        flowDelegateUserService.updateDeletegatedUserConfirm(delegateId, confirmStatus);
        return ResponseResult.success();
    }

    /**
     * 列出我被委托的列表。
     *
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/listMyDelegated")
    public ResponseResult<MyPageData<FlowDelegateUserVo>> listMyDelegated(@MyRequestBody MyPageParam pageParam) {
        try (Page<FlowDelegateUser> page = PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize())) {
            List<FlowDelegateUser> flowDelegateUserList =
                    flowDelegateUserService.getFlowDelegateUserListByMyUserId(null, false);
            return ResponseResult.success(MyPageUtil.makeResponseData(flowDelegateUserList, FlowDelegateUserVo.class));
        }
    }

    /**
     * 列出有效的委托人列表的字典数据。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @GetMapping("/listDictEffectiveDelegate")
    public ResponseResult<List<Map<String, Object>>> listDictEffectiveDelegate() {
        List<FlowDelegateUser> resultList =
                flowDelegateUserService.getFlowDelegateUserListByMyUserId(null, true);
        return ResponseResult.success(MyCommonUtil.toDictDataList(
                resultList, FlowDelegateUser::getCreateUserId, FlowDelegateUser::getCreateShowName));
    }
}